// @flow
import React from 'react'
import styles from './ChannelData.css'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { Spin, notification } from 'antd'
import R from 'ramda'

type Props = {
  goToCondition: Function,
  channelData: Array<any>,
  deviceData: Object,
  sensorType: string,
  filterData: Function,
  panelYear: string
}
type States = {
  selectBoardVisible: boolean,
  selectedChannel: any,
  targetData: Array<Object>,
  loading: boolean
}
// const commonData = ['通道1', '通道2', '通道3', '通道4']
// const allData = ['通道2', '通道1', '通道13', '通道4', '通道5', '通道6', '通道7', '通道8', '通道9', '通道15']
class ChannelData extends React.Component {
  props: Props
  state: States
  interval: number
  openChannelSelect: Function
  selectChannel: Function
  getTargetData: Function
  reduceChannel: Function
  addChannel: Function
  closeSelectBoard: Function
  channelInterval: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      selectBoardVisible: false,
      // selectedChannel: 0, // 选中的通道的索引（默认第一个通道）
      selectedChannel: 'allIndex', // 选中的通道的索引（默认全部通道）
      targetData: [],
      loading: true
    }
    this.openChannelSelect = this.openChannelSelect.bind(this)
    this.selectChannel = this.selectChannel.bind(this)
    this.getTargetData = this.getTargetData.bind(this)
    this.reduceChannel = this.reduceChannel.bind(this)
    this.addChannel = this.addChannel.bind(this)
    this.closeSelectBoard = this.closeSelectBoard.bind(this)
    this.channelInterval = this.channelInterval.bind(this)
  }
  componentWillMount () {
    const { channelData } = this.props
    const { selectedChannel } = this.state
    const channelId = selectedChannel === 'allIndex' ? 'all' : Number(channelData[selectedChannel].id)
    this.getTargetData(this.props, channelId)
    this.channelInterval()
  }
  componentWillReceiveProps (nextProps: Props) {
    if (!R.equals(nextProps, this.props)) {
      this.setState({
        selectedChannel: 'allIndex'
      }, () => {
        this.channelInterval()
      })
    }
  }
  componentWillUnmount () {
    clearInterval(this.interval)
  }

  channelInterval () {
    const component = this
    const { channelData } = this.props
    const { selectedChannel } = this.state
    const channelId = selectedChannel === 'allIndex' ? 'all' : Number(channelData[selectedChannel].id)
    clearInterval(this.interval)
    this.interval = setInterval(function () {
      component.getTargetData(component.props, channelId)
    }, 5000)
  }

  closeSelectBoard () {
    this.setState({
      selectBoardVisible: false
    })
  }
  addChannel () {
    const { channelData } = this.props
    const { selectedChannel } = this.state
    const len = channelData.length
    if (selectedChannel === (len - 1)) {
      this.setState({
        selectedChannel: 0
      }, () => {
        this.channelInterval()
      })
    } else {
      this.setState({
        selectedChannel: selectedChannel + 1
      }, () => {
        this.channelInterval()
      })
    }
  }
  reduceChannel () {
    const { channelData } = this.props
    const { selectedChannel } = this.state
    const len = channelData.length
    if (selectedChannel === 0) {
      this.setState({
        selectedChannel: len - 1
      }, () => {
        this.channelInterval()
      })
    } else {
      this.setState({
        selectedChannel: selectedChannel - 1
      }, () => {
        this.channelInterval()
      })
    }
  }

  // 关键指标与选择的某个通道指标的数据
  getTargetData (props: Props, channelId: number) {
    const { deviceData, sensorType, channelData } = props
    const { selectedChannel } = this.state
    if (channelId === 'all') { // 选择全部通道后执行的方法（显示所有通道的关键指标：type=2是关键指标，type=1非关键指标）
      universalFetch(`${__SERVICE_API__}device/devices/${deviceData.id}/monitors?` +
        `sensor-type=${sensorType}&kmxvalue=kmxvalue&type=2`)
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          this.setState({
            targetData: json.result.map((d, i) => {
              d['kmxVariableName'] = d['channelName'] + '___' + d['kmxVariableName']
              return d
            }),
            loading: false
          })
          // props.filterData([], false) // 关键指标是空
        })
        .catch((error) => {
          handleFetchError(error)
          this.setState({
            loading: false
          })
          notification['error']({
            message: '指标请求异常',
            description: error.message
          })
        })
    } else {  // 选择单个通道后执行的方法（&type=1非关键指标，不传参数请求所有指标）
      universalFetch(`${__SERVICE_API__}device/devices/${deviceData.id}/monitors?` +
        `sensor-type=${sensorType}&channel-id=${channelId}&kmxvalue=kmxvalue`)
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          this.setState({
            targetData: json.result,
            loading: false
          })
          // props.filterData(json.result, this.state.loading)
        })
        .catch((error) => {
          handleFetchError(error)
          this.setState({
            loading: false
          })
          // props.filterData([], this.state.loading)
          notification['error']({
            message: '指标请求异常',
            description: error.message
          })
        })
        // 动态的核心指标请求数据
      // universalFetch(`${__SERVICE_API__}device/devices/${deviceData.id}/monitors?` +
      //   `sensor-type=${sensorType}&channel-id=${channelId}&kmxvalue=kmxvalue&type=2`)
      //   .then((res) => res.json())
      //   .then((json) => {
      //     if (json.code !== 200000) {
      //       throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      //     }
      //     // 核心指标默认的通道
      //     const defaultChannel = [channelId + '__' + channelData[selectedChannel]['name']]
      //     const result = json.result.map((d, i) => {
      //       d['defaultChannel'] = defaultChannel
      //       return d
      //     })
      //     props.filterData(result, false)
      //   })
      //   .catch(() => {
      //   })
    }

    // 固定的核心指标（设备状态、启停机次数、转速）
    universalFetch(`${__SERVICE_API__}device/devices/${deviceData.id}/panel?year=${props.panelYear}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        props.filterData(json.result, false)
      })
      .catch(() => {
      })
  }
  openChannelSelect () {
    this.setState({
      selectBoardVisible: true
    }, () => {
      document.getElementById('selectBoard').focus()
    })
  }
  selectChannel (item: any, index: number) {
    this.getTargetData(this.props, item)
    this.setState({
      selectedChannel: index,
      selectBoardVisible: false
    }, () => {
      this.channelInterval()
    })
  }
  render () {
    const { goToCondition, channelData } = this.props
    const { selectBoardVisible, selectedChannel, targetData } = this.state
    const selectChannel = this.selectChannel
    return (
      <div className={styles['main']}>
        <div className={styles['status-bar']}>
          <span className={styles['channel-title']}>
            <span className={styles['left']} onClick={this.reduceChannel}>
              <i className='fa fa-angle-left' aria-hidden='true' />
            </span>
            <span className={styles['title']} onClick={this.openChannelSelect}>
              {selectedChannel === 'allIndex' ? '全部通道' : channelData[selectedChannel]['name']}
            </span>
            <span className={styles['right']} onClick={this.addChannel}>
              <i className='fa fa-angle-right' aria-hidden='true' />
            </span>
          </span>
          <span className={styles['status-info']}>
            <span className={styles['normal']}>
              <span className={styles['status-normal']} />
              正常
            </span>
            <span className={styles['info']}>
              <span className={styles['status-info']} />
              预警
            </span>
            <span className={styles['danger']}>
              <span className={styles['status-danger']} />
              危险
            </span>
          </span>
        </div>
        {
          selectBoardVisible
          ? <div className={styles['channel-select-board']} tabIndex='0' id='selectBoard'
            onBlur={this.closeSelectBoard}>
            <div className={styles['select-board-title']}>
              <h2>{selectedChannel === 'allIndex' ? '全部通道' : channelData[selectedChannel]['name']}</h2>
            </div>
            {
            // <div className={styles['common-channel']}>
            //   <h3>常用通道</h3>
            //   {
            //     commonData.map((item, index) => {
            //       return <div className={styles['channel-item']} key={index} onClick={this.selectChannel}>
            //         {item}
            //       </div>
            //     })
            //   }
            // </div>
            }
            <div className={styles['all-channel']}>
              {
                // <h3>全部通道</h3>
              }
              <div className={styles['channel-item']} key={'allIndex'}
                onClick={function () { selectChannel('all', 'allIndex') }}>
                全部通道
              </div>
              {
                channelData.map((item, index) => {
                  return <div className={styles['channel-item']} key={index}
                    onClick={function () { selectChannel(item.id, index) }}>
                    {item.name}
                  </div>
                })
              }
            </div>
          </div>
          : false
        }
        <Spin spinning={this.state.loading}>
          <div className={styles['var-status-container']}>
            {
              targetData.length > 0
              ? targetData.map((item, i) => {
                // let value = Math.round((item.kmxValue + item.kmxUnit) * 100) / 100
                let value = item.kmxValue
                if (!isNaN(item.kmxValue)) {
                  value = Math.round(item.kmxValue * 100) / 100
                  if (value > 10000 || value < -10000) {
                    value = value.toExponential(2)
                  }
                }
                let bgClass
                const limitType = item.limitType
                if (limitType === '2') {
                  bgClass = styles['danger-item']
                } else if (limitType === '1') {
                  bgClass = styles['danger-info']
                } else {
                  bgClass = styles['danger-normal']
                }
                const channel = [item.channelId + '__' + item.channelName]
                return <div className={styles['var-item']} key={i}
                  onClick={function () { goToCondition(item, channel) }}>
                  <span className={styles['var-item-title']}>
                    {item.kmxVariableName}
                  </span>
                  <div className={styles['var-item-bar']}>
                    <span className={styles['var-status'] + ` ${bgClass}`} />
                    {value}
                  </div>
                </div>
              }) : false
            }
          </div>
        </Spin>
      </div>
    )
  }
}

export default ChannelData
